import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:qunaimedical/components/custom_avatar.dart';
import 'package:qunaimedical/components/item_quick_menu.dart';
import 'package:qunaimedical/components/item_option.dart';
import 'package:qunaimedical/components/primary_button.dart';
import 'package:qunaimedical/components/shimmer_indicator.dart';
import 'package:qunaimedical/im/im_utils.dart';
import 'package:qunaimedical/init/provider.dart';
import 'package:qunaimedical/models/qa_user.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/pages/feedback.dart';
import 'package:qunaimedical/pages/login.dart';
import 'package:qunaimedical/pages/profile.dart';
import 'package:qunaimedical/pages/web_page.dart';
import 'package:qunaimedical/utils/auth_util.dart';
import 'package:qunaimedical/utils/common_util.dart';
import 'package:qunaimedical/utils/dialog_util.dart';
import 'package:qunaimedical/utils/navigator_util.dart';
import 'package:qunaimedical/utils/sp_util.dart';
import 'package:qunaimedical/values/configs.dart';
import 'package:qunaimedical/values/urls.dart';

class MePage extends StatefulWidget {
  @override
  _MePageState createState() => _MePageState();
}

class _MePageState extends State<MePage> {
  RefreshController _refreshController = RefreshController();

  @override
  Widget build(BuildContext context) {
    QAUser? user = context.watch<StoreInfo>().qaUser;
    return Scaffold(
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(
            height: MediaQuery.of(context).padding.top,
            color: Color(0xff39e7ba),
          ),
          Expanded(
            child: SmartRefresher(
              controller: _refreshController,
              enablePullUp: false,
              enablePullDown: true,
              header: ShimmerHeader(
                baseColor: Color(0xff39e7ba),
                text: Text(
                  "",
                  style: TextStyle(color: Colors.grey, fontSize: 22),
                ),
              ),
              onRefresh: user == null
                  ? () => _refreshController.refreshCompleted()
                  : _refresh,
              child: ListView(
                padding: EdgeInsets.symmetric(vertical: 0),
                children: [
                  _buildHeader(context),
                  _buildDataOptions(),
                  _buildSecondryOptions(),
                  ItemOption(
                    imagePath: 'assets/images/ic_feedback.png',
                    text: '后续反馈',
                    onTap: () => pushTo(context, FeedbackPage()),
                  ),
                  ItemOption(
                    imagePath: 'assets/images/ic_about.png',
                    text: '关于我们',
                    onTap: () => pushTo(
                        context, WebPage(url: Urls.ABOUT, title: "关于我们")),
                  ),
                  ItemOption(
                      imagePath: 'assets/images/ic_version.png',
                      text: '当前版本',
                      hideRightArrow: true,
                      trailing: FutureBuilder<PackageInfo>(
                        future: PackageInfo.fromPlatform(),
                        builder: ((BuildContext context,
                            AsyncSnapshot<PackageInfo> snapshot) {
                          String version = '';
                          if (snapshot.hasData) {
                            version =
                                '${snapshot.data!.version} (${snapshot.data!.buildNumber})';
                          }
                          return Text(version,
                              style: Theme.of(context).textTheme.caption);
                        }),
                      )),
                  Offstage(
                    offstage: user == null,
                    child: PrimaryButton(
                      '退出',
                      onPressed: () => _logout(context),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _login() {
    Navigator.pushNamed(context, LoginPage.routeName);
  }

  void _logout(BuildContext context) {
    DialogUtil.showAlertDialog(context, '确认退出？', onPressed: () {
      Navigator.pop(context);
      AuthUtil.logout(context);
      IMUtils.signOut();
    });
  }

  void _refresh() async {
    QAUser user = context.read<StoreInfo>().qaUser!;
    String url = "${Urls.USER_INFO}${user.id}";
    try {
      Response response = await XHttp.instance.get(url);
      if (mounted) {
        if (response.statusCode == 200 && response.data != null) {
          user.name = response.data["data"]["name"];
          context.read<StoreInfo>().updateQAUser(user);
        }
      }
    } on DioError catch (e) {
      if (mounted) {
        CommonUtil.catchDioError(e);
      }
    }
    _refreshController.refreshCompleted();
  }

  Container _buildHeader(BuildContext context) {
    QAUser? user = context.watch<StoreInfo>().qaUser;
    return Container(
      padding: EdgeInsets.only(
        top: 0,
        left: 16,
        right: 16,
        bottom: 0,
      ),
      height: 180,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("assets/images/bg_header.png"),
          fit: BoxFit.cover,
        ),
      ),
      child: Stack(
        alignment: Alignment.centerLeft,
        children: [
          Positioned(
            child: Offstage(
              offstage: user != null,
              child: InkWell(
                onTap: () {
                  _login();
                },
                child: Text(
                  '登录/注册',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
          ),
          Positioned(
            child: Offstage(
              offstage: user == null,
              child: InkWell(
                onTap: () {
                  Navigator.pushNamed(context, ProfilePage.routeName);
                },
                child: user == null
                    ? Container()
                    : Row(
                        children: [
                          CustomAvatar(size: 80, avatarUrl: user.photo),
                          SizedBox(width: 10),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Text(
                                  user.name,
                                  maxLines: 1,
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 24,
                                    fontWeight: FontWeight.bold,
                                  ),
                                  overflow: TextOverflow.ellipsis,
                                ),
                                _buildChip(user.companyId),
                                Container(
                                  padding: const EdgeInsets.only(top: 3),
                                  child: Row(
                                    children: [
                                      _buildChip(user.officeId),
                                      SizedBox(width: 8),
                                      _buildChip(user.level),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Icon(
                            Icons.chevron_right_outlined,
                            color: Colors.white,
                          )
                        ],
                      ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSecondryOptions() {
    List<String> images = [
      'assets/images/me_ziliao.png',
      'assets/images/me_ziliaobianji.png',
      'assets/images/me_richeng.png',
      'assets/images/me_mimaxiugai.png',
      'assets/images/me_zhuanjia.png',
      'assets/images/me_zhibo.png',
      'assets/images/me_guanzhu.png', // 关注和收藏，图标相同
      'assets/images/me_shoucang.png',
      'assets/images/me_zixun.png',
      'images/chat_input_bar_more_show.png',
    ];

    List<String> titles = [
      '个人资料',
      '资料编辑',
      '我的日程',
      '密码修改',
      '专家库',
      '会诊直播',
      '我的关注',
      '我的收藏',
      '医患咨询',
      '扩展',
    ];

    List<String> urls = [
      Urls.ME_PERSON_INFO,
      Urls.ME_EDIT_INFO,
      Urls.ME_SCHEDULE,
      Urls.ME_PASSWORD_CHANGE,
      Urls.ME_EXPERTS,
      Urls.ME_MEET_LIVE,
      Urls.ME_FOCUS,
      Urls.ME_FAVOURITE,
      Urls.ME_PATIENT_TALK,
      Urls.ME_MORE_PLUGIN,
    ];

    return Container(
      color: Colors.white,
      child: Column(
        children: [
          Row(
            children: List.generate(
              4,
              (index) => Expanded(
                child: ItemQuickMenu(
                  height: 80,
                  text: titles[index],
                  imagePath: images[index],
                  onTap: () {
                    if (index == 0) {
                      _goToPageWithUrl(
                          "${urls[index]}${SPUtil.getQAUser()?.id}");
                    } else if (index == 1) {
                      navigateTo(context, ProfilePage.routeName,
                          authStateRequired: true);
                    } else {
                      _goToPageWithUrl(urls[index]);
                    }
                  },
                ),
              ),
            ),
          ),
          Row(
            children: List.generate(
              4,
              (index) => Expanded(
                child: ItemQuickMenu(
                  height: 80,
                  text: titles[index + 4],
                  imagePath: images[index + 4],
                  onTap: () => _goToPageWithUrl(urls[index + 4]),
                ),
              ),
            ),
          ),
          Row(
            children: List.generate(
              2,
              (index) => ItemQuickMenu(
                width: MediaQuery.of(context).size.width / 4,
                height: 80,
                text: titles[index + 8],
                imagePath: images[index + 8],
                onTap: () => _goToPageWithUrl(urls[index + 8]),
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget _buildDataOptions() {
    return Container(
      transform: Matrix4.translationValues(0, -16, 0),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        ),
      ),
      child: Row(children: [
        Expanded(
          child: ItemQuickMenu(
            text: '我申请的',
            imagePath: "assets/images/me_shenqing.png",
            onTap: () => toMyConsultation(context, MyConsultationType.mystart),
          ),
        ),
        Expanded(
          child: ItemQuickMenu(
            text: '我收到的',
            height: 100,
            imagePath: "assets/images/me_shoudao.png",
            onTap: () =>
                toMyConsultation(context, MyConsultationType.myreceive),
          ),
        ),
        Expanded(
          child: ItemQuickMenu(
            text: '学术会议',
            imagePath: "assets/images/me_xueshuhuiyi.png",
            onTap: () => _goToPageWithUrl(Urls.ME_SERVER_API_1_3),
          ),
        ),
        Expanded(
          child: ItemQuickMenu(
            text: '学术预约',
            imagePath: "assets/images/me_xueshuyuyue.png",
            onTap: () => _goToPageWithUrl(Urls.ME_ACADEMIC_MEET),
          ),
        ),
      ]),
    );
  }

  void _goToPageWithUrl(String url) {
    pushTo(context, WebPage(url: url), authStateRequired: true);
  }

  Widget _buildChip(String? value) {
    return Offstage(
      offstage: value == null || value == "",
      child: Container(
        margin: const EdgeInsets.only(top: 4.0),
        child: Text(
          value ?? "",
          style: TextStyle(fontSize: 12, color: Colors.white),
        ),
        padding: EdgeInsets.symmetric(
          horizontal: 8,
          vertical: 2,
        ),
        decoration: BoxDecoration(
          border: new Border.all(
            color: Colors.white,
            width: 0.5,
          ),
          borderRadius: new BorderRadius.all(Radius.circular(20)),
        ),
      ),
    );
  }
}
